<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { onActivated, onMounted, ref, watch } from 'vue';

import { cloneDeep } from '@vben/utils';

import { ElMessage } from 'element-plus';

import { reqTrade } from '#/api/exchange-center';
import { reqSupportedSymbolByName } from '#/api/system';

import { optionsBuySell } from '../indexData';
import Buy from './Buy.vue';
import Sell from './Sell.vue';

export interface IUser {
  id: string;
  name: string;
  group: string;
  disabled: boolean;
}
export interface IGroup {
  id: string;
  name: string;
  disabled: boolean;
}

const props = defineProps(['platform']);

const placeBuyRef = ref<FormInstance>();
const placeSellRef = ref<FormInstance>();
const placeFormRef = ref<FormInstance>();
const buyloading = ref(false);
const sellloading = ref(false);
const allloading = ref(false);
const params = ref({
  symbol: null,
  repeat_times: 1,
  interval_sec: 0,
  platform_id: props.platform.id,
});
watch(
  () => props.platform.id,
  () => {
    params.value.platform_id = props.platform.id;
  },
);

const openRules = ref({
  symbol: [{ required: true, message: '请输入品种', trigger: 'change' }],
  leverage: [{ required: true, message: '请输入杠杆', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  level: [{ required: true, message: '请选择' }],
});

interface ISymbol {
  id: number;
  symbol: string;
}

const supportSymbol = ref<ISymbol[]>([]);

const getSupportSymbol = async () => {
  const result = await reqSupportedSymbolByName(props.platform.name);
  supportSymbol.value = result;
};

const buyData = ref({
  price: null,
  amount: null,
  quantity: null,
  group: [] as IGroup[] | string[],
  leverage: 1,
  level: null,
  account: [] as IUser[] | string[],
  place_delay: 0,
  cancel_delay: 0,
  isAutoRevoke: true,
});

const sellData = ref({
  price: null,
  amount: null,
  quantity: null,
  group: [] as IGroup[] | string[],
  leverage: 1,
  level: null,
  account: [] as IUser[] | string[],
  place_delay: 0,
  cancel_delay: 0,
  isAutoRevoke: true,
});

const handlePlace = async (formEl: FormInstance | undefined, type: number) => {
  if (!formEl) return;
  await formEl.validate();

  const buy_valid = async () => {
    return (
      (await placeBuyRef.value?.validate()) &&
      (buyData.value.account.length > 0 || buyData.value.group.length > 0)
    );
  };
  const sell_valid = async () => {
    return (
      (await placeSellRef.value?.validate()) &&
      (sellData.value.account.length > 0 || sellData.value.group.length > 0)
    );
  };

  if (type === 1) {
    const buyValid = await buy_valid();

    if (!buyValid) {
      ElMessage.error('请检查买方的必填项');
      return;
    }
  } else if (type === 2) {
    const sellValid = await sell_valid();
    if (!sellValid) {
      ElMessage.error('请检查卖方的必填项');
      return;
    }
  } else {
    const buyValid = await buy_valid();
    const sellValid = await sell_valid();

    if (!buyValid || !sellValid) {
      ElMessage.error('请检查买方或卖方的必填项');
      return;
    }
    allloading.value = true;
  }

  buyloading.value = type === 1;
  sellloading.value = type === 2;

  const sendBuyData = cloneDeep(buyData.value);
  const sendSellData = cloneDeep(sellData.value);

  sendBuyData.group = sendBuyData.group.map((item) => (item as IGroup).id);
  sendBuyData.account = sendBuyData.account.map((item) => (item as IUser).id);
  sendBuyData.cancel_delay = sendBuyData.isAutoRevoke
    ? sendBuyData.cancel_delay
    : -1;

  sendSellData.group = sendSellData.group.map((item) => (item as IGroup).id);
  sendSellData.account = sendSellData.account.map((item) => (item as IUser).id);
  sendSellData.cancel_delay = sendSellData.isAutoRevoke
    ? sendSellData.cancel_delay
    : -1;

  const data = {
    ...params.value,
    buy_command: sendBuyData,
    sell_command: sendSellData,
    type_submit: type,
  };
  // console.log('sendBuyData', sendBuyData);
  // console.log('sendSellData', sendSellData);
  // console.log('dta', data);
  // return;

  reqTrade(data)
    .then(() => {
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
    })
    .finally(() => {
      buyloading.value = false;
      sellloading.value = false;
      allloading.value = false;
    });
};

watch(
  () => params.value.repeat_times,
  (newVal) => {
    if (newVal === 1) {
      params.value.interval_sec = 0;
    } else if (newVal === null) {
      params.value.repeat_times = 1;
    }
  },
);

onActivated(() => {
  getSupportSymbol();
});

onMounted(() => {
  getSupportSymbol();
});
</script>

<template>
  <div class="place-order">
    <el-form
      class="form"
      :model="params"
      :rules="openRules"
      label-width="100px"
      ref="placeFormRef"
    >
      <div class="form-content">
        <div class="title-wrapper">
          <div class="title">
            <div class="title-buy">买方</div>
            <div class="title-sell">卖方</div>
          </div>
        </div>
        <div class="symbol">
          <el-form-item label="下单品种" prop="symbol">
            <el-select
              v-model="params.symbol"
              placeholder=""
              style="width: 100%"
              :options="supportSymbol"
            >
              <template #default>
                <el-option
                  v-for="item in supportSymbol"
                  :key="item.id"
                  :label="item.symbol"
                  :value="item.symbol"
                />
              </template>
            </el-select>
          </el-form-item>
        </div>
        <div class="combined-box">
          <div class="box-half">
            <Buy
              ref="placeBuyRef"
              v-model="buyData"
              disabled-name="disabledA"
              change-disabled-name="disabledB"
              :options-buy-sell="optionsBuySell"
            />
          </div>
          <!-- 垂直分隔线 -->
          <div class="vertical-divider"></div>
          <div class="box-half">
            <Sell
              ref="placeSellRef"
              v-model="sellData"
              disabled-name="disabledB"
              change-disabled-name="disabledA"
              :options-buy-sell="optionsBuySell"
            />
          </div>
        </div>
        <el-row class="interval">
          <el-col :span="12">
            <el-form-item label="重复次数" class="pr-8">
              <el-input-number
                v-model="params.repeat_times"
                placeholder=""
                style="width: 100%"
                type="number"
                :controls="false"
                :min="1"
                :max="99999"
                :precision="0"
                class="inp"
              >
                <template #suffix>
                  <span>次</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="间隔" class="pr-10">
              <el-input-number
                v-model="params.interval_sec"
                class="numInput"
                placeholder=""
                style="width: 100%"
                type="number"
                :controls="false"
                :min="0"
                :precision="0"
                :disabled="params.repeat_times === 1"
                onkeypress="return( /[\d.]/.test(String.fromCharCode(event.keyCode)))"
              >
                <template #suffix>
                  <span>秒</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="flex justify-center p-3">
        <el-button
          type="success"
          @click="handlePlace(placeFormRef, 1)"
          :loading="buyloading"
          style="width: 150px"
        >
          单买
        </el-button>
        <el-button
          type="danger"
          @click="handlePlace(placeFormRef, 2)"
          :loading="sellloading"
          style="width: 150px"
        >
          单卖
        </el-button>
      </div>
      <div class="flex justify-center p-3">
        <el-button
          type="primary"
          @click="handlePlace(placeFormRef, 3)"
          :loading="allloading"
          style="width: 310px"
        >
          对敲
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
.place-order {
  height: 100%;
  padding: 15px;
  background-color: hsl(var(--background));
  border-radius: 4px;

  .interval {
    display: flex;
  }

  .but {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 124px;
    height: 34px;
    margin-left: 20px;
    color: #fff;
    cursor: pointer;
    border-radius: 24px;

    .t1 {
      height: 12px;
      font-size: 12px;
      line-height: 12px;
    }

    .t2 {
      margin-left: 4px;
      font-size: 14px;
      line-height: 12px;
    }

    &.buy {
      background-color: #35cd8f;
      border: #35cd8f;
    }

    &.sell {
      background-color: #ff8080;
      border: #ff8080;
    }
  }
}

.select-price {
  ::v-deep(.el-select__selection) {
    text-align: center;

    .el-select__placeholder {
      color: var(--color);
    }
  }
}

.buy-select {
  .buy-option {
    color: #35cd8f;
  }

  .sell-option {
    color: #ff8080;
  }
}

.title-wrapper {
  background-color: #fafafa;
  border-radius: 8px;

  .title {
    display: flex;
    justify-content: space-around;
    // border: 1px solid #ccc;
    text-align: center;

    .title-buy {
      width: 50%;
      padding: 12px;
      color: #fff;
      background-color: #13bf79;
      border-radius: 6px 0 0;
    }

    .title-sell {
      width: 50%;
      padding: 12px;
      color: #fff;
      background-color: #ee6060;
      border-radius: 0 6px 0 0;
    }
  }
}

.form-content {
  border: 1px solid #ccc;
  border-radius: 6px;
}

.symbol {
  padding-top: 12px;
  padding-right: 12px;
  border-bottom: 1px solid #ccc;
}

.combined-box {
  display: flex;
  overflow: hidden;

  .box-half {
    padding: 12px;
  }
}

.vertical-divider {
  width: 1px;
  background-color: #ccc;
}

.interval {
  padding-top: 12px;
  border-top: 1px solid #ccc;
}
</style>
